
import { assetsDB } from '@/indexDB/index'
import { DEFAULT_STRATEGY_LIST, STRATEGY_LIST_KEY } from '@/views/strategy/model'
import { ref } from 'vue'

export interface StrategyItem {
  id?: string | number
  /**
   * @deprecated 已弃用，请使用 id 来代替。
   */
  code?: string // 旧主键
  name: string
  remarks?: string
}

export const strategyList = ref<StrategyItem[]>([])

export const initStrategyDB = async () => {
  const arr = await assetsDB.strategyList.toArray()

  if (!arr.length) {

    const listStr = localStorage.getItem(STRATEGY_LIST_KEY)
    const list = listStr ? JSON.parse(listStr) : DEFAULT_STRATEGY_LIST

    await assetsDB.strategyList.bulkAdd(list)

    console.log('--策略初始化成功');
    // 顺便初始化以便全局使用
    updateStrategyList()
  } else {
    updateStrategyList()
  }
}

export const updateStrategyList = async () => {
  strategyList.value = await assetsDB.strategyList.toArray()
  return Promise.resolve(strategyList.value)
}